package com.jrh.web.member;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jrh.biz.member.Oauth2Service;
import com.jrh.domain.entity.User;
import com.jrh.scribe.builder.ServiceBuilder;
import com.jrh.scribe.builder.api.QqzoneApi;
import com.jrh.scribe.builder.api.SinaWeiboApi;
import com.jrh.scribe.extractors.TokenExtractorImpl;
import com.jrh.scribe.model.OAuthRequest;
import com.jrh.scribe.model.Response;
import com.jrh.scribe.model.SignatureType;
import com.jrh.scribe.model.Token;
import com.jrh.scribe.model.Verb;
import com.jrh.scribe.model.Verifier;
import com.jrh.scribe.oauth.OAuthService;
import com.jrh.web.member.tools.UserAuthUtil;

/**
 * 外部网站登录
 * 
 * @author jasen.hsu.cn@gmail.com 2012-7-16 下午9:32:17
 */

@Controller
@RequestMapping("/connect")
public class ExtLoginController {

    private static final Logger logger                  = LoggerFactory.getLogger(ExtLoginController.class);

    @Autowired
    private Oauth2Service       oauth2Service;

    private OAuthService        qqOAuthService;

    private OAuthService        weiboOAuthService;

    private static final String WEIBO_OAUTH_LOGIN_URL   = "https://api.weibo.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=http://www.jiaruhe.com/connect/weibo";

    private static final String qzone_get_user_info_url = "http://openapi.qzone.qq.com/user/get_user_info";

    private static final String user_home_url           = "redirect:/user/me.htm";

    /**
     * 淘宝帐号登录
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/taobao")
    public String loginFromTaobao(HttpServletRequest request, HttpServletResponse response) {
        if (UserAuthUtil.isSignIn(request, response)) {
            return user_home_url;
        }
        String params = request.getParameter("top_parameters");
        String sign = request.getParameter("top_sign");
        if (StringUtils.isBlank(params) || StringUtils.isBlank(sign)) {
            return "redirect:" + "https://oauth.taobao.com/authorize?response_type=user&client_id="
                   + oauth2Service.getTaobaoAppkey() + "&redirect_uri=" + oauth2Service.getTaobaoCallbackUrl();
        }
        User user = oauth2Service.getTaobaoUser(params, sign);
        logger.error("" + user);
        if (user == null) {
            return "redirect:" + "https://oauth.taobao.com/authorize?response_type=user&client_id="
                   + oauth2Service.getTaobaoAppkey() + "&redirect_uri=" + oauth2Service.getTaobaoCallbackUrl();
        }
        UserAuthUtil.signIn(user, request, response);
        return user_home_url;
    }

    @RequestMapping("/qq")
    public String login2QQ(HttpServletRequest request, HttpServletResponse response) {
        if (UserAuthUtil.isSignIn(request, response)) {
            return user_home_url;
        }
        synchronized (OAuthService.class) {
            if (qqOAuthService == null) {
                qqOAuthService = new ServiceBuilder().provider(QqzoneApi.class).apiKey(oauth2Service.getQqAppkey()).apiSecret(oauth2Service.getQqAppSecret()).callback(oauth2Service.getQqCallbackUrl()).signatureType(SignatureType.QueryString).build();
            }
        }
        Token reqToken = qqOAuthService.getRequestToken();
        // 保存secret到session以备后面调用open api时候用
        request.getSession().setAttribute("qq_srt", reqToken.getSecret());
        String qqAuthUrl = qqOAuthService.getAuthorizationUrl(reqToken) + "&oauth_callback="
                           + oauth2Service.getQqCallbackUrl() + "&oauth_consumer_key=" + oauth2Service.getQqAppkey();
        return "redirect:" + qqAuthUrl;
    }

    /**
     * QQ帐号登录
     * 
     * @return
     */
    @RequestMapping("/callback/qq")
    public String loginFromQQ(HttpServletRequest request, HttpServletResponse response) {
        if (UserAuthUtil.isSignIn(request, response)) {
            return user_home_url;
        }
        if (qqOAuthService == null || request.getParameter("oauth_token") == null) {
            return "redirect:" + "/connect/qq.htm";
        }
        Token reqToken = new Token(request.getParameter("oauth_token"),
                                   (String) request.getSession().getAttribute("qq_srt"));
        Verifier verifier = new Verifier(request.getParameter("oauth_vericode"));
        Token accessToken = qqOAuthService.getAccessToken(reqToken, verifier);
        Pattern p = Pattern.compile("openid=([^&]+)");
        String openid = TokenExtractorImpl.extract(accessToken.getRawResponse(), p);
        String urlGetOpenidInfo = qzone_get_user_info_url;
        OAuthRequest treq = new OAuthRequest(Verb.GET, urlGetOpenidInfo);
        treq.addQuerystringParameter("openid", openid);
        qqOAuthService.signRequest(accessToken, treq);
        Response oauthResp = treq.send();
        String body = oauthResp.getBody();
        User user = oauth2Service.getQqUser(body, openid);
        if (user == null) {
            return "redirect:" + "/connect/qq.htm";
        }
        UserAuthUtil.signIn(user, request, response);
        return user_home_url;
    }

    @RequestMapping("/weibo")
    public String login2Weibo(HttpServletRequest request, HttpServletResponse response) {
        if (UserAuthUtil.isSignIn(request, response)) {
            return user_home_url;
        }
        synchronized (OAuthService.class) {
            if (weiboOAuthService == null) {
                weiboOAuthService = new ServiceBuilder().provider(SinaWeiboApi.class).apiKey(oauth2Service.getWeiboAppkey()).apiSecret(oauth2Service.getWeiboAppSecret()).callback(oauth2Service.getWeiboCallbackUrl()).signatureType(SignatureType.QueryString).build();
            }
        }
        Token reqToken = weiboOAuthService.getRequestToken();
        // 保存secret到session以备后面调用open api时候用
        request.getSession().setAttribute("weibo_srt", reqToken.getSecret());
        String qqAuthUrl = weiboOAuthService.getAuthorizationUrl(reqToken) + "&oauth_callback="
                           + oauth2Service.getQqCallbackUrl() + "&oauth_consumer_key=" + oauth2Service.getQqAppkey();
        return "redirect:" + qqAuthUrl;
    }

    /**
     * 微博帐号登录
     * 
     * @return
     */
    @RequestMapping("/callback/weibo")
    public String loginFromWeibo(HttpServletRequest request, HttpServletResponse response) {
        if (UserAuthUtil.isSignIn(request, response)) {
            return user_home_url;
        }
        if (weiboOAuthService == null || request.getParameter("oauth_token") == null) {
            return "redirect:" + "/connect/weibo.htm";
        }
        Token reqToken = new Token(request.getParameter("oauth_token"),
                                   (String) request.getSession().getAttribute("weibo_srt"));
        Verifier verifier = new Verifier(request.getParameter("oauth_vericode"));
        Token accessToken = weiboOAuthService.getAccessToken(reqToken, verifier);
        Pattern p = Pattern.compile("openid=([^&]+)");
        String openid = TokenExtractorImpl.extract(accessToken.getRawResponse(), p);
        String urlGetOpenidInfo = qzone_get_user_info_url;
        OAuthRequest treq = new OAuthRequest(Verb.GET, urlGetOpenidInfo);
        treq.addQuerystringParameter("openid", openid);
        weiboOAuthService.signRequest(accessToken, treq);
        Response oauthResp = treq.send();
        String body = oauthResp.getBody();
        User user = oauth2Service.getQqUser(body, openid);
        // TODO:XXX
        if (user == null) {
            return "redirect:" + "/connect/weibo.htm";
        }
        UserAuthUtil.signIn(user, request, response);
        return user_home_url;
    }
}
